<template>
  <div class="login-container">
    <el-card class="login-box" shadow="hover">
      <h3 style="text-align: center; margin-bottom: 20px;">求职者登录</h3>
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="80px">
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" @keyup.enter.native="submit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit" :loading="loading" style="width: 100%">登 录</el-button>
        </el-form-item>
        <div style="text-align: center;">
          <span>还没有账号？</span>
          <el-button type="text" @click="$router.push('/user_register')">立即注册</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'UserLogin',
  data() {
    return {
      loading: false,
      form: {
        account: '',
        password: ''
      },
      rules: {
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    };
  },
  methods: {
    submit() {
      this.$refs.loginForm.validate(valid => {
        if (!valid) return;

        this.loading = true;
        request.post('/User_login', this.form)
          .then(res => {
            this.loading = false;
            const data = res.data;
            if (data.code === 1 && data.data) {
              // 保存 token 和用户信息
             
              localStorage.setItem('user_token', data.data.token);
              localStorage.setItem('currentUser', JSON.stringify(data.data));
              console.log(data.data);
              
              this.$message.success('登录成功！');
              this.$router.push('/user_main_page');
            } else {
              this.$message.error(data.msg || '账号或密码错误');
            }
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('网络错误，请检查服务是否启动');
            console.error(err);
          });
      });
    }
  },
  created() {
    // 如果已登录，自动跳转
    // if (localStorage.getItem('user_token')) {
    //   this.$router.push('/user_main_page');
    // }
  }
};
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  border-radius: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>